package com.ljm.commom.web.audit.aspect;

import com.ljm.commom.web.audit.annotation.AuditLog;
import com.ljm.commom.web.audit.enums.BusinessOperatorType;
import com.ljm.commom.web.audit.enums.BusinessType;
import com.ljm.common.constants.SysConstants;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author HuamingChen
 * @Date 2020/8/8
 */
@Configuration
@Aspect
public class AuditAspect {
    private Logger logger= LoggerFactory.getLogger(AuditAspect.class);
    @Pointcut(value = "@annotation(com.ljm.commom.web.audit.annotation.AuditLog)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object handleAround(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AuditLog annotation = method.getAnnotation(AuditLog.class);
        BusinessOperatorType businessOperatorType = annotation.operatorType();
        String loginName = SysConstants.LOGIN_NAME_TL.get();
        BusinessType businessType = annotation.businessType();
        String businessName = annotation.businessName();
        boolean saveRequestData = annotation.isSaveRequestData();
        try {
            Object proceed = joinPoint.proceed();
            return proceed;
        } finally {
            // 后续入库或上传到搜索引擎
            logger.info("审计日志: [{}] {}【{}】使用了{}功能", LocalDateTime.now(),businessOperatorType.getMsg(),loginName,businessName);
        }
    }
}
